package com.zhudi.develop_demo_as;

import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestHandle;
import com.zhudi.develop.util.ZhudiDebugLog;
import com.zhudi.develop.util.ZhudiToastSingle;
import com.zhudi.develop.view.ZhudiOnListViewListener;
import com.zhudi.develop.view.ZhudiPullListView;
import com.zhudi.develop_demo_as.adapter.BaseListViewAdapter;
import com.zhudi.develop_demo_as.network.MyHttpClient;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * Created by wangdan on 15-1-16.
 */
public abstract class BaseListViewFragment extends BaseFragment {
    @Bind(R.id.lv)
    ZhudiPullListView lv;
    @Bind(R.id.layoutLoading)
    LinearLayout loading;
    @Bind(R.id.layoutLoadFailed)
    LinearLayout loadFail;
    @Bind(R.id.layoutEmpty)
    LinearLayout loadEmpty;
    @Bind(R.id.tvContent)
    TextView tvContent;
    /** Fragment当前状态是否可见 */
    //protected boolean isVisible;
    private BaseListViewAdapter mDataAdapter;
    private int currentPage;
    private MyHttpClient client;
    private List<RequestHandle> requestHandles = new ArrayList<RequestHandle>();
    @Override
    protected int getLayoutView() {
        return R.layout.fragment_order_type;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        client = new MyHttpClient();
        currentPage = 0;
    }

    /** Fragment当前状态是否可见 */
    protected boolean isVisible;

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if(getUserVisibleHint()) {
            isVisible = true;
            //onVisible();
        } else {
            isVisible = false;
            //onInvisible();
        }
    }


    /**
     * 可见
     */
    protected void onVisible() {
        //lazyLoad();
        ZhudiDebugLog.d("onVisible------->");
        if (isVisible)
            getData(currentPage,true);
    }

    /**
     * 不可见
     */
    protected void onInvisible() {

    }


//    /**
//     * 延迟加载
//     * 子类必须重写此方法
//     */
//    protected abstract void lazyLoad();
//
//    @Override
//    public void setUserVisibleHint(boolean isVisibleToUser) {
//        super.setUserVisibleHint(isVisibleToUser);
//        if (isVisibleToUser){
//             //fragment可见时执行加载数据
//            isVisible = true;
//        } else {
//             //不可见时不加载
//            isVisible = false;
//        }
//    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mDataAdapter = getAdapter();
        lv.setOverScrollMode(View.OVER_SCROLL_NEVER);
        lv.setPullRefreshEnable(true);// 打开下拉刷新功能
        lv.setPullLoadEnable(true);// 开启加载更多功能
        lv.setAdapter(mDataAdapter);
        lv.setZhudiOnListViewListener(new ZhudiOnListViewListener() {
            @Override
            public void onRefresh() {
                currentPage = 0;
                getData(currentPage, false);
            }

            @Override
            public void onLoadMore() {
                currentPage = 0;
                getData(currentPage, false);
            }
        });

        if (isVisible)
            getData(currentPage,true);
    }


    private void getData(int page,boolean refreshFlag){
        if (refreshFlag)
            layoutView(1);
        else
            layoutView(0);
        RequestHandle rh;
        String url = getItemURL(page);
        if (url == null)
            return;
        rh = client.get(getActivity(), url, null, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                ZhudiDebugLog.d(new String(responseBody));
                onSuccessData(new String(responseBody));
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                layoutView(2);
            }

            @Override
            public void onFinish() {
                layoutView(0);
            }
        });
        requestHandles.add(rh);
    }

    private void onSuccessData(String result){
        tvContent.setText(result);
        JSONObject root;
        try {
            root = new JSONObject(result);
//            if (root.getInt("code") == 1) {
//            } else if (root.getInt("code") == -100) {
//            } else {
//            }
           // Object object = getGsonType().parse(root);
           // mDataAdapter.resetDataSet((List) object);
            mDataAdapter.notifyDataSetChanged();

        } catch (JSONException e1) {
            ZhudiToastSingle.showToast(getActivity(),"数据解析错误", Toast.LENGTH_SHORT,-1);
        }
    }

    /**0全部隐藏 1显示加载 2显示错误 3显示暂无数据*/
    private void layoutView(int i){
        if (i == 0){
            loading.setVisibility(View.GONE);
            loadFail.setVisibility(View.GONE);
            loadEmpty.setVisibility(View.GONE);
        } else if(i == 1){
            loading.setVisibility(View.VISIBLE);
            loadFail.setVisibility(View.GONE);
            loadEmpty.setVisibility(View.GONE);
        } else if(i == 2){
            loading.setVisibility(View.GONE);
            loadFail.setVisibility(View.VISIBLE);
            loadEmpty.setVisibility(View.GONE);
        } else if(i == 3){
            loading.setVisibility(View.GONE);
            loadFail.setVisibility(View.GONE);
            loadEmpty.setVisibility(View.VISIBLE);
        }
        lv.setVisibility(View.GONE);
    }

    @OnClick(R.id.layoutReload)
    public void layoutReLoad(){
        getData(currentPage,false);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        for (RequestHandle rh:requestHandles){
            if (!rh.isCancelled() && !rh.isFinished()) {
                rh.cancel(true);
            }
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ZhudiDebugLog.d("onDestroyView--->");
    }

    protected abstract String getItemURL(int page);

    protected abstract BaseListViewAdapter getAdapter();

    protected abstract JsonObjectParser getGsonType();

    protected abstract Object getModel();

}
